<template>
	<el-drawer v-model="isShowDrawer" direction="rtl" :before-close="handleClose" size="1100px" :close-on-click-modal="isReadOnly">
		<template #header="{ titleId, titleClass }">
			<div class="zs-drawer-header" :id="titleId" :class="titleClass">
				<i class="icon-b-item zs-icon zs-text-blue zs-space-right-sm"></i>
				<div class="zs-title zs-text-black">{{ currentRow?.reportName }}</div>
			</div>
		</template>

		<template #default>
			<el-container class="zs-drawer-container">
				<div class="zs-drawer-content-whole zs-layout-flex-col overflow-auto">
					<div class="top-box zs-layout-flex-row zs-layout-justify-between zs-space-bottom">
						<span class="zs-text-gray">单位：万元</span>
						<span class="zs-text-gray">截止日期：{{ stopDate }}</span>
					</div>
					<div class="zs-layout-flex-row zs-space-bottom-bg">
						<div class="zs-space-right-bg zs-full-item">
							<el-table class="report-table" :data="leftList" v-loading="loading" :row-class-name="tableRowClassName">
								<el-table-column prop="order" label="序号" width="80" align="center" />
								<el-table-column label="项目" align="left">
									<template #default="{ row }">
										<span :class="{ 'padding-left-m': row.level == 3 }">{{ row.projectName }}</span>
									</template>
								</el-table-column>
								<el-table-column prop="content" label="金额" align="right" width="160">
									<template #default="{ row }">
										<el-input v-if="row.isWrite" :class="{ 'no-shadow-input': handleType == 'info' }" maxlength="10" size="small" v-model="row.content" placeholder=" " :disabled="isReadOnly" @input="validateInput(row)" @blur="handleBlur(row)" />
										<span class="padding-right-m" v-else>{{ row.content }}</span>
									</template>
								</el-table-column>
							</el-table>
						</div>
						<div class="zs-space-left-bg zs-full-item">
							<el-table class="report-table" :data="rightList" v-loading="loading" :row-class-name="tableRowClassName">
								<el-table-column prop="order" label="序号" width="80" align="center" />
								<el-table-column label="项目" align="left">
									<template #default="{ row }">
										<span :class="{ 'padding-left-m': row.level == 3 }">{{ row.projectName }}</span>
									</template>
								</el-table-column>
								<el-table-column prop="content" label="金额" align="right" width="160">
									<template #default="{ row }">
										<el-input v-if="row.isWrite" :class="{ 'no-shadow-input': handleType == 'info' }" maxlength="10" size="small" v-model="row.content" placeholder=" " :disabled="isReadOnly" @input="validateInput(row)" @blur="handleBlur(row)" />
										<span class="padding-right-m" v-else>{{ row.content }}</span>
									</template>
								</el-table-column>
							</el-table>
						</div>
					</div>
					<el-input v-model="analysisNote" :maxlength="3000" show-word-limit type="textarea" :placeholder="handleType != 'info' ? '请填写说明文' : ''" :autosize="{ minRows: 3 }" :disabled="isReadOnly" />
				</div>
			</el-container>
		</template>

		<template v-if="handleType != 'info'" #footer>
			<el-button class="zs-btn-md zs-btn-primary" @click="doConfirm">提交</el-button>
		</template>
	</el-drawer>
</template>

<script setup>
	import { fundsSourceInfoApi, fundsSourceSaveApi } from '@/api/SpecialReport/settlementReport';
	import { ref, watch, nextTick } from 'vue';
	import { ElMessage } from 'element-plus';
	import { toThousands } from '@/utils/number-util';

	const props = defineProps({
		isShow: { type: Boolean, default: false },
		isReadOnly: { type: Boolean, default: true },
		handleType: { type: String, default: '' },
		currentRow: { type: Object },
	});

	const emit = defineEmits(['close']);
	let isShowDrawer = ref(props.isShow);
	let stopDate = ref('');

	watch(
		() => props.isShow,
		newVal => {
			isShowDrawer.value = newVal;
			nextTick(() => {
				newVal && getInfo();
			});
		},
	);

	let loading = ref(false);

	let leftList = ref([
		{ order: '一', projectName: '来源合计', filedName: 'sourceTotal', content: '', level: 1, isWrite: true },
		{ order: '(一)', projectName: '股东投入资本', filedName: 'inFunds', content: '', level: 2, isWrite: true },
		{ order: '(二)', projectName: '经营及投资净流入', filedName: 'inFlows', content: '', level: 2, isWrite: true },
		{ order: '1', projectName: '历年累计已结转利润', filedName: 'inFlows1', content: '', level: 3, isWrite: true },
		{ order: '2', projectName: '加:非付现成本-折1日', filedName: 'inFlows2', content: '', level: 3, isWrite: true },
		{ order: '3', projectName: '应收账款', filedName: 'inFlows3', content: '', level: 3, isWrite: true },
		{ order: '4', projectName: '应收利息、股利', filedName: 'inFlows4', content: '', level: 3, isWrite: true },
		{ order: '5', projectName: '预收账款', filedName: 'inFlows5', content: '', level: 3, isWrite: true },
		{ order: '6', projectName: '应付未付经营支出', filedName: 'inFlows6', content: '', level: 3, isWrite: true },
		{ order: '7', projectName: '应付未付税金', filedName: 'inFlows7', content: '', level: 3, isWrite: true },
		{ order: '8', projectName: '应付利息', filedName: 'inFlows8', content: '', level: 3, isWrite: true },
		{ order: '9', projectName: '预付账款', filedName: 'inFlows9', content: '', level: 3, isWrite: true },
		{ order: '(三)', projectName: '向股东分配股利', filedName: 'inFlows10', content: '', level: 2, isWrite: true },
		{ order: '(四)', projectName: '融资资金余额', filedName: 'inFlows11', content: '', level: 2, isWrite: true },
	]);

	let rightList = ref([
		{ order: '二', projectName: '占用合计', filedName: 'occupyTotal', content: '', level: 1, isWrite: true },
		{ order: '(一)', projectName: '存货及其他未结转经营成本支出', filedName: 'expenditure', content: '', level: 2, isWrite: true },
		{ order: '1', projectName: '完工物业', filedName: 'expenditure1', content: '', level: 3, isWrite: true },
		{ order: '2', projectName: '在建物业', filedName: 'expenditure2', content: '', level: 3, isWrite: true },
		{ order: '3', projectName: '土地储备', filedName: 'expenditure3', content: '', level: 3, isWrite: true },
		{ order: '4', projectName: '其他存货', filedName: 'expenditure4', content: '', level: 3, isWrite: true },
		{ order: '(二)', projectName: '运营资产及其他资产(原值)', filedName: 'originVal', content: '', level: 2, isWrite: true },
		{ order: '(三)', projectName: '投资支出', filedName: 'investOut', content: '', level: 2, isWrite: true },
		{ order: '1', projectName: '对外股权投资', filedName: 'investOut1', content: '', level: 3, isWrite: true },
		{ order: '2', projectName: '金融资产投资', filedName: 'investOut2', content: '', level: 3, isWrite: true },
		{ order: '3', projectName: '投资预付款(诚意金、订金等)', filedName: 'investOut3', content: '', level: 3, isWrite: true },
		{ order: '(四)', projectName: '集团关联单位占用资金净额', filedName: 'innerNetAmount', content: '', level: 2, isWrite: true },
		{ order: '(五)', projectName: '外单位占用资金净额', filedName: 'outNetAmount', content: '', level: 2, isWrite: true },
		{ order: '(六)', projectName: '货币资金余额', filedName: 'fundsBalance', content: '', level: 2, isWrite: true },
	]);

	//数据源
	const getInfo = async () => {
		let res = await fundsSourceInfoApi(props.currentRow.id);
		if (res.data.code != 200 || !res.data.data) return;
		let result = Object.assign(res.data.data);
		analysisNote.value = result.analysisNote;
		stopDate.value = result.stopDate;
		let setVal = list => {
			for (let i in result) {
				list.forEach(item => {
					if (item.filedName == i) {
						if (item.isWrite) {
							item.content = props.handleType == 'info' ? result[i] : result[i] && result[i] != '-' ? clearComma(result[i]) : result[i];
						} else {
							item.content = result[i] ? result[i] : '-';
						}
					}
				});
			}
		};
		setVal(leftList.value);
		setVal(rightList.value);
	};

	//提交
	const analysisNote = ref('');
	const doConfirm = async () => {
		let params = {};
		leftList.value.forEach(item => {
			params[item.filedName] = !isNaN(item.content) && item.content != '-' ? toThousands(item.content) : item.content;
		});
		rightList.value.forEach(item => {
			params[item.filedName] = !isNaN(item.content) && item.content != '-' ? toThousands(item.content) : item.content;
		});
		params.reportDetailId = props.currentRow.id;
		params.analysisNote = analysisNote.value;
		let res = await fundsSourceSaveApi(params);
		if (res.data.code == 200) {
			ElMessage({
				message: '提交成功',
				type: 'success',
			});
			isShowDrawer.value = false;
			emit('close', { isShow: false, isRefresh: true });
		}
	};

	//表格颜色
	const tableRowClassName = ({ row }) => {
		if (row.level === 1) {
			return 'level-one-bg';
		} else if (row.level === 2) {
			return 'level-two-bg';
		}
		return '';
	};

	// 只允许输入正负数的验证函数
	const validateInput = row => {
		// 移除非法字符，保留数字、负号、小数点
		row.content = row.content
			.replace(/[^0-9.-]/g, '') // 只允许数字、小数点和负号
			.replace(/(?!^)-/g, '') // 负号只能在第一位，移除其他位置的负号
			.replace(/(?!\d*\.\d*$)\./g, '') // 只允许一个小数点，移除多余的小数点
			.replace(/(\.\d{2})\d*/g, '$1'); // 保留最多四位小数

		// 如果小数点开头，自动补0
		if (row.content.startsWith('.')) {
			row.content = '0' + row.content;
		}

		// 只输入负号时不做进一步处理
		if (row.content === '-') return;
	};

	// 校验最后一位是不是 .
	const handleBlur = row => {
		if (row.content.endsWith('.')) {
			row.content = row.content.slice(0, -1); // 移除最后一位小数点
		}
	};

	const clearComma = (data) => {
		return data ? data.replace(/,|%/g, '') : '';
	}

	//关闭抽屉
	const handleClose = done => {
		emit('close', { isShow: false });
		done();
	};
</script>

<style scoped lang="scss">
	.zs-drawer-content-whole {
		background: #ffffff;
		width: 100%;
		padding: 20px;
		overflow: hidden;
		.top-box {
			border-bottom: 1px solid #f1f1f1;
			padding-bottom: 15px;
		}
		.padding-left-m {
			padding-left: 20px;
		}
		.padding-right-m {
			padding-right: 15px;
		}
		:deep(.report-table) {
			.level-one-bg {
				--el-table-tr-bg-color: #eee2dd !important;
			}
			.level-two-bg {
				--el-table-tr-bg-color: #eef4fe !important;
			}
			.el-input.is-disabled .el-input__wrapper {
				--el-table-tr-bg-color: transparent !important;
				background-color: transparent !important;
			}
			.el-input__wrapper {
				.el-input__inner {
					text-align: right !important;
					font-size: 14px;
				}
			}
			.no-shadow-input {
				.el-input__wrapper {
					box-shadow: none !important;
				}
			}
		}
	}
	.overflow-auto {
		overflow-y: auto !important;
	}
</style>
